package com.javaweb.blogcite.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
public class CaptchaController {

    // 注入用于生成验证码的DefaultKaptcha实例
    @Resource
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/res/captcha")
    public void getCaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        // 生成验证码文本
        String captchaText = defaultKaptcha.createText();
        // 将验证码文本存入Session
        httpServletRequest.getSession().setAttribute("captchaText", captchaText);
        // 生成验证码图片
        BufferedImage bufferedImage = defaultKaptcha.createImage(captchaText);

        try {
            // 将验证码图片转换为PNG格式字节数据存入outputStream
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", outputStream);

            // 把图片字节数据写入HTTP响应输出流，返回给客户端
            httpServletResponse.setContentType("image/png");
            httpServletResponse.getOutputStream().write(outputStream.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}